package com.dhxt.springcloud.config;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * @Description:配置实体实体管理器工厂
 * @author hp
 * @date 2017年7月16日 上午9:49:27
 */
@Configuration
public class DataBaseConfig {

	//此处非要加个前缀才行 ？
	@Bean
	@ConfigurationProperties(prefix = "jdbc")
	public DataSource dataSource(){
		return DataSourceBuilder.create().build();
	}

	/*
	 * @Primary public DruidDataSource jpadataSource() throws Exception {
	 * 
	 * InputStream is = null; Properties props = null;
	 * 
	 * try { is = this.getClass().getClassLoader().getResourceAsStream(
	 * "dataSource.properties"); props = new Properties(); props.load(is); }
	 * finally { if (is != null) is.close(); }
	 * 
	 * DruidDataSource ds = (DruidDataSource)
	 * DruidDataSourceFactory.createDataSource(props); return ds; }
	 */

	@Bean
	public EntityManagerFactory entityManagerFactory() throws Exception {

		LocalContainerEntityManagerFactoryBean fb = new LocalContainerEntityManagerFactoryBean();
		fb.setDataSource(dataSource());

		HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
		jpaVendorAdapter.setGenerateDdl(false);
		jpaVendorAdapter.setShowSql(false);
		jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");
		fb.setJpaVendorAdapter(jpaVendorAdapter);
		fb.setPackagesToScan("com.dhxt.springcloud.entity");
		fb.setPersistenceUnitName("spTest");
		fb.setPersistenceProviderClass(HibernatePersistenceProvider.class);
		fb.afterPropertiesSet();

		return fb.getObject();
	}

	@Bean
	public PlatformTransactionManager transactionManager() throws Exception {
		JpaTransactionManager txManager = new JpaTransactionManager();
		txManager.setEntityManagerFactory(entityManagerFactory());
		txManager.afterPropertiesSet();
		return txManager;
	}
}